package com.cloudfun.campusshare.configuration.interceptors;

import com.cloudfun.campusshare.common.constant.Code;
import com.cloudfun.campusshare.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * Created by Huqin on 2020/1/6
 */
@Slf4j
public class PageableHandlerMethodArgumentResolver extends org.springframework.data.web.PageableHandlerMethodArgumentResolver {

    @Override
    public Pageable resolveArgument(MethodParameter methodParameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        Pageable pageable = super.resolveArgument(methodParameter, mavContainer, webRequest, binderFactory);
        int pageNumber = pageable.getPageNumber();
        if (pageNumber < 1) {
            log.error("分页查询异常，页码小于1");
            throw new BusinessException(Code.PARAMETER_ERROR);
        }
        Sort sort;
        if (pageable.getSort().equals(Sort.unsorted())) {
            sort = Sort.by(Sort.Direction.DESC, "updateTime");
        } else {
            sort = pageable.getSort();
        }
        return PageRequest.of(pageNumber - 1, pageable.getPageSize(), sort);
    }
}
